package com.sparrow.rpc.socket.session;

import com.sparrow.rpc.manager.RpcClientManager;
import com.sparrow.rpc.socket.RpcClient;
import com.sparrow.socket.tcp.session.Session;
import com.sparrow.socket.tcp.session.listener.SessionListener;
import com.sparrow.socket.tcp.session.manager.AbstractSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class RpcClientSessionManager extends AbstractSessionManager<String, RpcSession> {

    @Autowired
    RpcClientManager clientManager;

    @PostConstruct
    public void init() {
        this.addListener(new SessionListener() {
            @Override
            public void onSessionBind(Session session) {

            }

            @Override
            public void onSessionRemove(Session session) {
                RpcSession rpcSession = (RpcSession) session;
                RpcClient rpcClient = clientManager.getRpcClient((String) rpcSession.getIdentity());
                if (rpcClient != null) {
                    rpcClient.closeSession();
                    rpcClient.connect();
                }
            }
        });
    }

}
